package com.bwie.service.impl;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginForm;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.mapper.UserMapper;
import com.bwie.service.UserService;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    UserMapper userMapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public void sendPhoneCode(String phone) {
        String numbers = RandomUtil.randomNumbers(4);
        System.out.println("验证码： " + numbers);
        MobileMessageUtil.sendMobileMessage(phone,numbers);
        redisTemplate.opsForValue().set(phone,numbers,5, TimeUnit.MINUTES);
    }

    @Override
    public R login(LoginForm loginForm) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,loginForm.getPhone());
        User user = userMapper.selectOne(wrapper);
        if(user==null){
            return R.ERROR(500,"用户手机号不存在");
        }
        if(!user.getPhone().equals(loginForm.getPhone())){
            return R.ERROR(500,"用户手机号错误");
        }
        String code = redisTemplate.opsForValue().get(user.getPhone());
        if(!loginForm.getCode().equals(code)){
            return R.ERROR(500,"验证码错误");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("id", user.getId()).compact();
        String key = "id" + user.getId();
        redisTemplate.opsForValue().set(key,token,5,TimeUnit.MINUTES);
        user.setPassword(null);
        user.setToken(token);
        return R.OK(user);
    }
}
